//
//  UICollectionViewTagCloudLayout.swift
//  fho
//
//  Created by 郭颢源 on 2021/3/29.
//

import UIKit

/// 云标签效果
/// https://upload-images.jianshu.io/upload_images/7565577-5109b697c67c72b2.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1200
class UICollectionViewTagCloudLayout: UICollectionViewFlowLayout {
        var maximumInteritemSpacing: CGFloat = 0.0
        
        override func prepare() {
            super.prepare()
        }
        
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            super.layoutAttributesForElements(in: rect)
            
            //使用系统帮我们计算好的结果
            guard let attributes = super.layoutAttributesForElements(in: rect) else {
                return nil
            }
            
            //第0个cell没有上一个cell，所以从1开始
            for i in 1..<attributes.count {
                let curAttr = attributes[i]
                let preAttr = attributes[i-1]
                
                let origin = preAttr.frame.maxX
                //根据maximumInteritemSpacing计算出的新的x位置
                let targetX = origin + maximumInteritemSpacing
                //只有系统计算的间距大于maximumInteritemSpacing时才进行调整
                if curAttr.frame.minX > targetX {
                    // 换行时不用调整
                    if targetX + curAttr.frame.width < collectionViewContentSize.width {
                        var frame = curAttr.frame
                        frame.origin.x = targetX
                        curAttr.frame = frame
                    }
                }
            }
            return attributes
        }
    }
/**
 使用：设置maximumInteritemSpacing为自己的需求即可了
 
 let layout = LLCustomClvFlowLayout()
 layout.maximumInteritemSpacing = 10.0
 */
